namespace SupplyChainWeb.Filters
{
    using System;
    using System.Threading;
    using System.Web.Mvc;

    /// <summary>
    /// Defines the <see cref="InitializeSimpleMembershipAttribute" />
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Defines the _initializer
        /// </summary>
        private static SimpleMembershipInitializer _initializer;

        /// <summary>
        /// Defines the _initializerLock
        /// </summary>
        private static object _initializerLock = new object();

        /// <summary>
        /// Defines the _isInitialized
        /// </summary>
        private static bool _isInitialized;

        /// <summary>
        /// The OnActionExecuting
        /// </summary>
        /// <param name="filterContext">The filterContext<see cref="ActionExecutingContext"/></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Ensure ASP.NET Simple Membership is initialized only once per app start
            LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
        }

        /// <summary>
        /// Defines the <see cref="SimpleMembershipInitializer" />
        /// </summary>
        private class SimpleMembershipInitializer
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="SimpleMembershipInitializer"/> class.
            /// </summary>
            public SimpleMembershipInitializer()
            {
            }
        }
    }
}
